package com.example.demo.security;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    /**
     * 根据用户名称查询用户信息 框架底层判断用户名密码是否正确
     *
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) {
        User user = null;
        try {
            user = userDao.findByUserName(s);
            List<GrantedAuthority> authorities = new ArrayList<>();
            List<String> perlist = getPermissionList();
            for (String s1 : perlist) {
                authorities.add(new SimpleGrantedAuthority(s1));
            }
            user.setAuthorities(authorities);
            System.out.println(user.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }


    /**
     * 模拟查数据库
     *
     * @return
     */
    public List<String> getPermissionList() {
        List<String> list = new ArrayList<>();
        list.add("jinxudong");
        list.add("init");
        list.add("selectOne");
        return list;
    }
}
